<svelte:options accessors />

<script lang="ts">
	import { Pagination, PaginationItem, Spinner } from 'flowbite-svelte'
	import { klineResultStore, updateKlineRequest } from './FudaStore'
	import { onDestroy, onMount } from 'svelte'
	import type { Unsubscriber } from 'svelte/motion'
	import { Label, Input, Button, InputAddon, ButtonGroup, Checkbox } from 'flowbite-svelte'
	import { page } from '$app/stores'
	import { KLINE_INIT_SIZE } from '$lib'

	$: isDisabled = true // Initially set to true to disable the range

	let page_num = 0
	let page_size = KLINE_INIT_SIZE

	let subscription: Unsubscriber
	onMount(() => {
		subscription = klineResultStore.subscribe((state) => {
			console.log('(KlineTableSlider.svelte) klineResultStore subscribe got state changed:', state)
			isDisabled = false
		})
	})
	onDestroy(() => {
		if (subscription) subscription()
	})

	const previous = () => {
		isDisabled = true
		page_num = page_num - 1
		updateKlineRequest(null, null, page_num, page_size)

		console.log(`Prev: page_num: ${page_num} page_size: ${page_size}`)
	}
	const next = () => {
		isDisabled = true
		page_num = page_num + 1
		updateKlineRequest(null, null, page_num, page_size)
		console.log(`Next: page_num: ${page_num} page_size: ${page_size}`)
	}

	const update = () => {
		isDisabled = true
		updateKlineRequest(null, null, page_num, page_size)
		console.log(`Update: page_num: ${page_num} page_size: ${page_size}`)
	}
</script>

<div class="flex flex-col relative w-full h-full">
	{#if isDisabled}
		<Button outline color="dark" class="w-full p-0 m-0">
			<Spinner class="me-3" size="4" />
			Loading ...
		</Button>
	{:else}
		<ButtonGroup class="w-full rounded-none p-0 m-0">
			<Button on:click={previous} class="bg-green-400" bind:disabled={isDisabled}>Prev</Button>
			<InputAddon>Page:</InputAddon>
			<Input
				id="input-addon"
				type="number"
				placeholder="0"
				bind:value={page_num}
				on:change={update}
				disabled
			/>
			<InputAddon>Size:</InputAddon>
			<Input
				id="input-addon"
				type="number"
				placeholder={KLINE_INIT_SIZE}
				bind:value={page_size}
				on:change={update}
				bind:disabled={isDisabled}
			/>
			<Button on:click={next} class="bg-green-400" bind:disabled={isDisabled}>Next</Button>
		</ButtonGroup>
	{/if}
</div>
